from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render, HttpResponse, get_object_or_404
from blog.models import Article
from blog_system.models import Like
from blog_system.forms import LoginForm
from django.core.exceptions import PermissionDenied
from django.contrib.auth import REDIRECT_FIELD_NAME, get_user_model
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.utils.decorators import method_decorator
from django.utils.http import is_safe_url
from django.views.decorators.debug import sensitive_post_parameters
from django.contrib import auth
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import never_cache
from django.core.cache import caches
from django.views.generic import FormView, RedirectView, View
import json
# Create your views here.


# 缓存
try:
    cache = caches['memcache']
except ImportError as e:
    cache = caches['default']


# 点赞
def like(request, pk):
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        ip = request.META['HTTP_X_FORWARDED_FOR']
    else:
        ip = request.META['REMOTE_ADDR']



    
    if request.method == 'POST':
        like_ips = cache.get(f'like_{pk}', [])

        if ip not in like_ips:

            if not Like.objects.filter(article_id=pk).exists():
                num = 1
                article = Article.objects.get(id=pk)
                Like.objects.create(num=num, article=article)
            else:
                article_like = Like.objects.filter(article_id=pk)[0]
                article_like.num += 1
                article_like.save()
                num = article_like.num

            # 更新缓存
            like_ips.append(ip)
            cache.set(f'like_{pk}', like_ips, 15 * 60 * 24)
            return HttpResponse(json.dumps({'success': True, 'like_num': num}), content_type="application/json")
        else:
            return HttpResponse(json.dumps({'success': False}), content_type="application/json")



# 登录
class LoginView(FormView):
    form_class = LoginForm
    template_name = 'user/login.html'
    success_url = '/'
    redirect_field_name = REDIRECT_FIELD_NAME

    @method_decorator(sensitive_post_parameters('password'))
    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, request, *args, **kwargs):
        return super(LoginView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        redirect_to = self.request.GET.get(self.redirect_field_name)
        if not redirect_to:
            redirect_to = '/'
        kwargs['redirect_to'] = redirect_to

        return super(LoginView, self).get_context_data(**kwargs)

    def form_valid(self, form):
        form = AuthenticationForm(data=self.request.POST, request=self.request)

        if form.is_valid():
            auth.login(self.request, form.get_user())
            return super(LoginView, self).form_valid(form)
        else:
            return self.render_to_response({'form': form})

    def get_success_url(self):
        redirect_to = self.request.POST.get(self.redirect_field_name)
        if not is_safe_url(url=redirect_to, allowed_hosts=[self.request.get_host()]):
            redirect_to = self.success_url
        return redirect_to

    def user_result(request):
        Type = request.GET.get('type')
        id = request.GET.get('id')

        user = get_object_or_404(get_user_model(), id=id)

        if user.is_active:
            return HttpResponseRedirect('/')

        if Type and Type in ['register', 'validation']:
            if Type == 'register':
                content = f"恭喜您注册成功，一封验证邮件已经发送到您 {user.email} 的邮箱，请验证您的邮箱后登录本站。"
                title = '注册成功'


class UserView(View):
    def post(self, request, *args, **kwargs):
        # 获取要对用户进行什么操作
        slug = self.kwargs.get('slug')

        if slug == 'login':
            return self.login(request)
        elif slug == "logout":
            return self.logout(request)
        elif slug == "register":
            return self.register(request)
        elif slug == "change_password":
            return self.change_password(request)
        elif slug == "forget_password":
            return self.forget_password(request)
        elif slug == "change_avatar":
            return self.change_avatar(request)
        elif slug == "reset_password":
            return self.reset_password(request)
        elif slug == "notification":
            return self.notification(request)

        raise PermissionDenied

    def get(self, request, *args, **kwargs):
        raise Http404

    def login(self, request):
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)

        errors = []

        if user:
            auth.login(request, user)
        else:
            errors.append("用户名或密码错误")

        return HttpResponse(json.dumps({'errors': errors}), content_type='application/json')

    def logout(self, request):
        if request.user.is_authenticated:
            auth.logout(request)
            return HttpResponse('OK')
        else:
            raise PermissionDenied

    def register(self, request):
        username = self.request.POST.get('username', '')
        password1 = self.request.POST.get('password1', '')
        password2 = self.request.POST.get('password2', '')
        email = self.request.POST.get('email', '')



    def change_password(self, request):
        pass

    def forget_password(self, request):
        pass

    def change_avatar(self, request):
        pass

    def reset_password(self, request):
        pass

    def notification(self, request):
        pass
